
import 'dart:developer';

import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/model/address_entity.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';

class GCAddressController extends GetxController {

  //刷新控件
  EasyRefreshController er_controller = EasyRefreshController();

  //分页请求page
  int page = 1;
  int size = 0;

  UserService userService = Get.find();
  var records = RxList<AddressDataRecord>.empty();

  var isEmpty = true.obs;

  addressAddTap() {
    Get.toNamed(Routes.ADDADDRESS);
  }

  Future<void> onRefresh() async {
    await requestAddressList(false);
  }

  Future<void> onLoadMore() async {
    await requestAddressList(true);
  }

  //isload yes上拉 false下啦
  requestAddressList([bool isload = false]) {
    if(isload) {
      page++;
    } else {
      page = 1;
    }

    HttpClient.request<AddressEntity>(
      url: UserAddrApi.usersAddr,
      method: Method.GET,
      params: {
        "uid" : userService.userInfo.uid,
        "current": page,
        "size": 5
      },
      onSuccess: (_,model) async {
        if (isload) {
          size += model.data.records.length;
          records.addAll(model.data.records);
          er_controller.finishLoad();
        } else {
          size = model.data.records.length;
          records.assignAll(model.data.records);
          er_controller.finishRefresh();
        }

        if (size == 0) {
          isEmpty.value = true;
        } else {
          isEmpty.value = false;
        }
        records.refresh();

      },
      onFailed: (err) async {
        page--;
        er_controller.finishRefresh();
      },
    );
  }

}
